<template>
  <!-- 人员弹窗 -->
  <a-modal
    centered
    :title="headerTitle"
    :visible="visible"
    ok-text=""
    width="1200px"
    @cancel="handleCancel"
    @ok="handleConfirm"
  >
    <a-row :gutter="10">
      <!-- 侧边栏 -->
      <a-col
        v-if="needTree"
        :span="6"
        style="border-right: 1px solid #d9d9d9"
      >
        <!-- <treeTest
      ></treeTest> -->
        <!-- 公司组织树搜索 -->
        <tree-organization
          v-if="visible"
          ref="treeOrganization"
          :checkable="true"
          :auto-select="false"
          :checkedKeys="treeCheckedKeys"
          :project-dept-org-id="projectDeptOrgId"
          @check="treeCheck"
          @select="treeSelect"
          @getData="getData"
          :selected-keys.sync="treeSelectKeys"
          :select-options.sync="treeSelectOptions"
        />
        <!-- @onOrgSelect="treeSelect" -->
        <!-- @loader="search" -->
      </a-col>
      <!-- 主内容 -->
      <a-col :span="needTree ? 18 : 24">
        <searchData
          ref="search"
          class="member-search"
          :showTitleName="false"
          :searchData="searchArr"
          @search="search"
        ></searchData>
        <div style="max-height: 150px; overflow: auto">
          <a-tag
            v-for="(person, index) in tableSelectedRows"
            :key="person.orgAndEmployerId"
            class="mb10"
            :closable="!person.isAdd"
            color="#108ee9"
            @close="() => handleClose(person, index)"
          >
            {{ person.name }}
          </a-tag>
        </div>

        <!-- <template v-if="tableData.length"> -->
        <!-- <a-button v-if="tableData.length == 0 || tableSelectedRows.length !== tableData.length" type="primary" @click="checkAll(true)">
            全选
          </a-button>
          <a-button v-else type="primary" @click="checkAll(false)">
            取消全选
          </a-button> -->
        <template>
          <span class="mr10p">已选 {{tableSelectedRows.length}} 条</span>
          <a
            :disabled="cancalAll"
            @click="checkAll(false)"
          >全部取消</a>
        </template>
        <!-- </template> -->
        <!-- 表格 -->
        <a-table
          :loading="tableLoading"
          :columns="columns"
          :row-key="record => record.orgAndEmployerId"
          :data-source="tableData"
          :row-selection="tableRowSelection"
          :pagination="{
              showQuickJumper: true,
              showSizeChanger: true,
              showTotal: total => `共搜索到 ${total} 条数据`
            }"
        />
        <!-- <b-table
          v-if="visible"
          ref="table"
          :select-config="{ use: true, type: isMutilple ? 'checkbox' : 'radio', rowKey:(row) => row.id || row.employeeId }"
          :scroll="{ x: 1200, y: 400 }"
          :columns="columns"
          :request="loadData"
          :out-selected-row-keys="tableSelectedKeys"
          @select-click="tableSelectClick"
        /> -->
      </a-col>
    </a-row>
    <!-- 页脚操作栏 -->
    <div
      v-if="isMutilple"
      slot="footer"
      class="btn_box"
    >
      <a-button
        type="primary"
        @click="handleCancel"
      >
        关闭
      </a-button>
      <a-button
        type="primary"
        @click="handleConfirm"
      >
        选中提交
      </a-button>
    </div>
    <div
      v-else
      slot="footer"
      class="btn_box"
    >
      <a-button
        type="default"
        @click="handleCancel"
      >
        取消
      </a-button>
      <a-button
        type="primary"
        @click="confirmSingle"
      >
        确定
      </a-button>
    </div>
  </a-modal>
</template>

<script>
import { STable } from '@/components' // 表格
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { getOrgsTree } from '@/api/subassembly/TreeSelectOrganization'
import { getOneOrgUsers, getListByOrgs } from '@/api/commons'
const searchArr = [
  // 搜索框
  {
    name: '名称',
    type: 'input',
    value: 'nameLike'
  },
  {
    name: '员工编号',
    value: 'jobNumLike',
    type: 'input'
  },
  {
    name: '电话',
    value: 'phoneLike',
    type: 'input'
  }
]
const jobStatusList = [
  { id: 0, name: '离职' },
  { id: 1, name: '在职' },
  { id: 2, name: '见习' }
]
const mutilpleColumn = [
  {
    title: '序号',
    width: '80px',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '员工名称',
    dataIndex: 'name',
    width: '150px'
  },
  {
    title: '员工编号',
    dataIndex: 'jobNum',
    width: '100px'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '100px',
    customRender(text, record, index) {
      return jobStatusList.find((item) => item.id == text).name
    }
  },
  {
    title: '电话号码',
    dataIndex: 'phone',
    width: '120px'
  },

  {
    title: '职务',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  }

  // {
  //   title: '操作',
  //   dataIndex: 'actions',
  //   width: '100px',
  //   scopedSlots: { customRender: 'actions' }
  // }
]

const singleColumn = [
  {
    title: '员工名称',
    dataIndex: 'name'
  },
  {
    title: '电话号码',
    dataIndex: 'phoneNum'
  },
  {
    title: '当前所在岗位',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  }
  // {
  //   title: '操作',
  //   dataIndex: 'actions',
  //   width: '100px',
  //   scopedSlots: { customRender: 'actions' }
  // }
]
export default {
  name: 'SelectPersonModal',
  components: {
    STable,
    TreeOrganization
  },
  props: {
    // 显隐控件
    // visible: {
    //   type: Boolean,
    //   default() {
    //     return false
    //   }
    // },
    projectDeptOrgId: {
      type: String,
      default() {
        return ''
      }
    },
    address: {
      type: String,
      default() {
        return ''
      }
    },
    // 表单
    form: {
      type: [Object],
      default() {
        return {}
      }
    },
    // 标题
    headerTitle: {
      type: String,
      default() {
        return '选择人员'
      }
    },
    // 列表api
    api: {
      type: Object,
      default() {
        return {}
      }
    },
    // 列表api请求axios
    loadList: {
      type: String,
      default() {
        return 'getList'
      }
    },
    outpersons: {
      type: Array,
      default() {
        return []
      }
    },
    // 是否显示组织树
    needTree: {
      type: Boolean,
      default: () => true
    },
    // 是否多选
    isMutilple: {
      type: Boolean,
      default: true
    },
    // 初始化之前
    beforeInit: [Function, Promise],
    // 禁用已选
    disabledOut: {
      type: Boolean,
      default: () => true
    },
    // 人员是否去重
    unRepeatPerson: {
      type: Boolean,
      default: () => true
    },
    //数据回显
    selectData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      searchArr,
      visible: false,
      tableLoading: false,
      queryParam: {},
      selectedOrg: [],
      treeCheckedKeys: [],
      treeCheckedOptions: [],
      treeSelectKeys: [],
      treeSelectOptions: [],
      tableSelectedKeys: [],
      tableSelectedRows: [],
      tableData: [],
      // 表格复选框配置
      // tableRowSelection: {
      //   type: 'checkbox', // or radio
      //   selectedRowKeys: this.tableSelectedKeys,
      //   onChange: this.onSelectChange,
      //   // onSelect(record, selected, selectedRows, nativeEvent) {
      //   //   console.log(record, selected, selectedRows, nativeEvent)
      //   // },
      //   // onSelectAll(selected, selectedRows, changeRows) {
      //   //   console.log(selected, selectedRows, changeRows)
      //   // },
      //   getCheckboxProps: (record) => ({
      //     props: {
      //       disabled: record.isAdd
      //     }
      //   })
      // },
      selectOptions: {},
      outTableData: [],
      init: false, // 初始化标识
      allTreeData: [],
      treeKeys: []
    }
  },
  computed: {
    orgQuery() {
      return {
        baseOrgType: 0, // 是否基础组织 0否 1是
        containVirtual: 0 //是否包含虚拟组织 0包含 1 不包含
      }
    },
    tableRowSelection() {
      const { tableSelectedKeys } = this
      return {
        type: 'checkbox', // or radio
        selectedRowKeys: tableSelectedKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isAdd
          }
        })
      }
    },
    // 树节点api
    apiTree() {
      return { getOrgsTree }
    },
    // 与父组件绑定visible
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (e) {
        this.$emit('update:visible', e)
      }
    },
    // 表格列表请求参数
    // args() {
    //   let args = {}
    //   // 添加树节点id
    //   if (this.treeCheckedKeys.length > 0) {
    //     args.rootOrgId = this.treeCheckedKeys[0]
    //   }
    //   // 若表单不为空
    //   if (Object.keys(this.form)?.length) {
    //     Object.assign(args, this.form)
    //   }
    //   // 若关键词存在
    //   if (Object.keys(this.queryParam).length) {
    //     Object.assign(args, this.queryParam)
    //   }
    //   // this.nameLike && (args.nameLike = this.nameLike)
    //   return args
    // },
    columns() {
      if (this.isMutilple) {
        return mutilpleColumn
      }
      return singleColumn
    },
    cancalAll() {
      return this.tableSelectedRows.filter((v) => !v.isAdd).length == 0
    }
  },
  watch: {
    visible(e) {
      if (e && this.needTree) {
        if (!this.$refs.treeOrganization) {
          this.$nextTick(() => {
            this.$refs.treeOrganization.getList().then((res) => {
              this.changeTreeChecked()
              this.initPage()
            })
          })
        } else {
          this.$nextTick(() => {
            this.initPage()
            // this.rowSelection.selectedRows = []
            // this.init === true && this.search()
          })
        }
      } else {
        // 重置关键词
        // this.nameLike = ''
        this.$refs.search.form.resetFields()
      }
    }
  },
  mounted() {},
  methods: {
    initPage() {
      const hasTreeChecked = this.treeCheckedKeys.length > 0
      const allkey = this.allTreeData.map((v) => v.id)
      this.treeKeys = allkey
      this.$nextTick(() => {
        this.getTableData(false, hasTreeChecked ? this.treeCheckedKeys : allkey)
      })
    },
    getData(data) {
      if (data.length) {
        this.$refs.treeOrganization.$refs.treeSearch.onExpand([data[0].id])
      }
      this.getTreeData(data)
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        if (item.type == '2') {
          this.allTreeData.push(item)
        }
        if (item.children && item.children.length) {
          this.getTreeData(item.children)
        }
      }
    },
    checkAll(type) {
      if (type) {
        this.tableSelectedRows = this.tableData
        this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
      } else {
        const list = this.tableData.filter((v) => v.isAdd)
        this.tableSelectedRows = [...list]
        this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
        this.changeTreeChecked()
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      let temp = []
      selectedRows.map((v) => {
        let res = this.tableSelectedRows.find((w) => v.orgAndEmployerId === w.orgAndEmployerId)
        if (!res) {
          temp.push(v)
        }
      })
      this.tableSelectedRows = this.tableSelectedRows.concat(temp)
      this.tableSelectedRows = this.tableSelectedRows.filter((v) => {
        return selectedRowKeys.find((w) => w === v.orgAndEmployerId)
      })

      this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
      // 表格数据勾选状态改变，联动树节点勾选改变
      this.changeTreeChecked()
    },
    changeTreeChecked() {
      const oids = []
      const temp = []
      const notemp = []
      this.tableSelectedRows.map((v) => {
        const has = oids.find((w) => w == v.orgId)
        if (!has) {
          oids.push(v.orgId)
        }
      })
      oids.map((v) => {
        const res = this.treeCheckedKeys.find((w) => w == v)
        if (!res) {
          notemp.push(v)
        }
      })
      this.treeCheckedKeys = this.treeCheckedKeys.concat(notemp)
      this.treeCheckedKeys = this.treeCheckedKeys.filter((v) => {
        return oids.find((w) => {
          return w == v
        })
      })
    },
    open(list) {
      this.visible = true
      this.outTableData = list
        ? list.map((v) => {
            if (this.disabledOut) v.isAdd = true
            v.orgAndEmployerId = this.unRepeatPerson ? v.id : v.orgId + '_' + v.id
            return v
          })
        : []
      this.tableSelectedKeys = this.outTableData.map((v) => v.orgAndEmployerId)
      this.tableSelectedRows = this.outTableData
    },
    getTableData(checked, orgIds) {
      if (!checked) this.tableLoading = true
      // 筛选所有选择项中属于“项目”的节点，避免传入所有节点id查询接口
      const treekeys = this.treeCheckedKeys.filter((v) => {
        return this.allTreeData.find((w) => {
          return v == w.id
        })
      })
      const params = {
        ...this.queryParam,
        orgIds: orgIds ? orgIds : treekeys
      }
      if (!checked) this.tableData = []
      getListByOrgs(params)
        .then((res) => {
          if (!checked) this.tableLoading = false
          const list = []
          for (let idx in res.data) {
            const obj = res.data[idx]
            obj.forEach((item, index) => {
              item.orgId = idx
              item.orgAndEmployerId = this.unRepeatPerson ? item.id : idx + '_' + item.id
              if (this.disabledOut && this.outTableData.find((v) => v.orgAndEmployerId == item.orgAndEmployerId)) {
                item.isAdd = true
              }
              const is = list.find((v) => {
                return v.orgAndEmployerId == item.orgAndEmployerId
              })
              if (!is) {
                list.push(item)
              }
            })
          }

          // this.tableSelectedRows = this.tableSelectedRows.filter((v) => {
          //   return list.find((w) => w.id == v.id)
          // })

          // 选择查出所有数据，但列表不展示
          if (checked) {
            const temp = []

            this.outTableData.map((v) => {
              let res = list.find((w) => v.orgAndEmployerId === w.orgAndEmployerId)
              if (!res) {
                temp.push(v)
              }
            })

            this.tableSelectedRows = list.concat(temp)
            this.tableSelectedKeys = this.tableSelectedRows.map((v) => v.orgAndEmployerId)
          } else {
            this.tableData = list
            if (this.selectData.length > 0) {
              this.selectData.map((item) => {
                this.tableData.map((tItem) => {
                  if (item.userId == tItem.userId) {
                    this.tableSelectedRows.push(tItem)
                    this.tableSelectedKeys.push(tItem.id)
                  }
                })
              })
              this.changeTreeChecked()
            }
          }
          // console.log(this.tableSelectedKeys)
        })
        .catch(() => {
          if (!checked) this.tableLoading = false
        })
    },
    treeCheck(checkedKeys, e) {
      // this.treeCheckedOptions = e.checkedNodes.filter((item, index) => {
      //   return item.data.props.type == '2'
      // }).map(v => v.data.props.dataRef)
      this.treeCheckedKeys = checkedKeys
      this.getTableData(true)
    },
    treeSelect(e, n) {
      if (n.selected) {
        const datas = n.selectedNodes[0].data.props.dataRef
        const ids = []
        const loop = (list) => {
          list.forEach((item, index) => {
            if (item.type == '2') ids.push(item.id)
            if (item.children) {
              loop(item.children)
            }
          })
        }
        loop([datas])
        this.treeKeys = ids
        this.getTableData(false, ids)
      } else {
        this.treeKeys = this.allTreeData.map((v) => v.id)
      }
    },
    loader() {
      // this.getTableData(false, this.treeSelectKeys)
    },
    /**
     * 单选时的确认操作
     */
    // confirmSingle() {
    //   if (!this.persons.length) {
    //     this.$message.warning('请添加人员')
    //     return
    //   }
    //   this.$emit('confirmSelect', this.persons[0])
    // },
    handleClose(removedPerson, index) {
      const key = this.tableSelectedRows[index]
      this.tableSelectedKeys.splice(index, 1)
      this.tableSelectedRows.splice(index, 1)
      this.changeTreeChecked()
    },
    handleConfirm() {
      let temp = []
      if (!this.selectData.length) {
        temp = !this.disabledOut
          ? this.tableSelectedRows
          : this.tableSelectedRows.filter((v) => {
              return !this.outTableData.find((w) => w.orgAndEmployerId === v.orgAndEmployerId)
            })
      } else {
        temp = this.tableSelectedRows
      }
      // if (temp.length == 0) {
      //   this.$message.warning('请选择要添加的人员')
      //   return
      // }
      this.visible = false
      this.$emit('confirm', temp)
    },
    filterPostPName(val) {
      if (val === null) return ''
      return (
        val.reduce &&
        val.reduce((pre, cur) => {
          return pre === '' ? cur : pre + '、' + cur
        }, '')
      )
    },
    // 头部搜索
    search(param) {
      if (param && Object.keys(param).length) {
        this.queryParam = {
          ...param
        }
      }
      // if (this.treeSelectKeys.length == 0) {
      //   this.$message.error('请先选择组织')
      //   return
      // }
      this.getTableData(false, this.treeKeys)
      // this.$refs.table.getData(null , true)
    },
    /**
     * 单选模式下，进行添加删除操作
     */
    // selectPerson(record) {
    //   // 已添加的数据需要删除
    //   if (record.isAdd) {
    //     record.isAdd = false
    //     const index = this.persons.findIndex((item) => item.id === record.id)
    //     this.persons.splice(index, 1)
    //     this.$refs.table.getData(null , true)
    //     return
    //   }
    //   if (this.persons.length > 0) {
    //     this.$message.warning('请先删除已添加人员再进行添加')
    //     return
    //   }
    //   record.isAdd = true
    //   this.$refs.table.getData(null , true)
    //   this.persons.push(record)
    // },
    // handleSubmit(record) {
    //   console.log('aa')
    //   record.isAdd = true
    //   this.$refs.table.getData(null , true)
    //   this.persons.push(record)
    //   // that.$emit('confirm', record)
    // },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
.ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
</style>